<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>发布-订阅模式-- 《Javascript 设计模式与开发实践》 | DiDi</title>
  <meta name="description" content="什么是发布-订阅模式发布订阅模式，它定义了对象之间的一种一对多的依赖关系，当一个对象的状态发生变化时，所有依赖于它的对象都会接收到通知。 生活中的发布-订阅模式其实我们生活中也有发布订阅模式的例子，比如小明想买某个楼盘的房子，他会打电话给售楼中心的销售人员，销售告诉他可惜卖完了，不过再过段时间就又有新房出售了，所以过了几天小明又来打电话询问房子的事情，结果新房又售罄了。小明很沮丧。我想现实生活中大">
<meta property="og:type" content="article">
<meta property="og:title" content="发布-订阅模式-- 《Javascript 设计模式与开发实践》">
<meta property="og:url" content="https://guoyayunhappy.gitee.io/didiblog/2023/02/08/design-pub-sub/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="什么是发布-订阅模式发布订阅模式，它定义了对象之间的一种一对多的依赖关系，当一个对象的状态发生变化时，所有依赖于它的对象都会接收到通知。 生活中的发布-订阅模式其实我们生活中也有发布订阅模式的例子，比如小明想买某个楼盘的房子，他会打电话给售楼中心的销售人员，销售告诉他可惜卖完了，不过再过段时间就又有新房出售了，所以过了几天小明又来打电话询问房子的事情，结果新房又售罄了。小明很沮丧。我想现实生活中大">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-02-08T04:42:36.000Z">
<meta property="article:modified_time" content="2023-02-08T04:42:48.836Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary">
  <!-- Canonical links -->
  <link rel="canonical" href="https://guoyayunhappy.gitee.io/didiblog/2023/02/08/design-pub-sub/index.html">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="images/favatar/idesign-logo.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/didiblog/css/style.css">

  
  
  
  
<meta name="generator" content="Hexo 7.3.0"></head>


<body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://gitee.com/GuoyayunHappy" target="_blank">
          <img class="img-circle img-rotate" src="/didiblog/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">一枚@大帅锅</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">CV工程师</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Shanghai, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/didiblog/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/didiblog/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/didiblog/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/didiblog/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/didiblog/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/didiblog/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://gitee.com/GuoyayunHappy" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/didiblog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>让coding更有趣!</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/JS/">JS</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/TS/">TS</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/">网站</a><span class="category-list-count">1</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/html/">html</a><span class="category-list-count">1</span></li></ul></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTML/" rel="tag">HTML</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTTP/" rel="tag">HTTP</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTTPS/" rel="tag">HTTPS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/JS/" rel="tag">JS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/Nodejs/" rel="tag">Nodejs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/Token/" rel="tag">Token</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/cookie/" rel="tag">cookie</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/js/" rel="tag">js</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/typescript/" rel="tag">typescript</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" rel="tag">性能优化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E7%AE%97%E6%B3%95/" rel="tag">算法</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E7%BC%93%E5%AD%98/" rel="tag">缓存</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">设计模式</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E8%B7%A8%E5%9F%9F/" rel="tag">跨域</a><span class="tag-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/didiblog/tags/HTML/" style="font-size: 13px;">HTML</a> <a href="/didiblog/tags/HTTP/" style="font-size: 13px;">HTTP</a> <a href="/didiblog/tags/HTTPS/" style="font-size: 13px;">HTTPS</a> <a href="/didiblog/tags/JS/" style="font-size: 13px;">JS</a> <a href="/didiblog/tags/Nodejs/" style="font-size: 13px;">Nodejs</a> <a href="/didiblog/tags/Token/" style="font-size: 13px;">Token</a> <a href="/didiblog/tags/cookie/" style="font-size: 13px;">cookie</a> <a href="/didiblog/tags/js/" style="font-size: 13px;">js</a> <a href="/didiblog/tags/typescript/" style="font-size: 13px;">typescript</a> <a href="/didiblog/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" style="font-size: 13px;">性能优化</a> <a href="/didiblog/tags/%E7%AE%97%E6%B3%95/" style="font-size: 13.5px;">算法</a> <a href="/didiblog/tags/%E7%BC%93%E5%AD%98/" style="font-size: 13px;">缓存</a> <a href="/didiblog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" style="font-size: 14px;">设计模式</a> <a href="/didiblog/tags/%E8%B7%A8%E5%9F%9F/" style="font-size: 13px;">跨域</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2025/07/">七月 2025</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2025/06/">六月 2025</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2024/03/">三月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2024/02/">二月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/12/">十二月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/10/">十月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/02/">二月 2023</a><span class="archive-list-count">7</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/07/28/browser-cache/" class="title">用代码实践浏览器的强缓存和协商缓存</a>
              </p>
              <p class="item-date">
                <time datetime="2025-07-28T06:54:53.000Z" itemprop="datePublished">2025-07-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/didiblog/categories/JS/">JS</a>
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/07/18/tail-call-optimization/" class="title">尾调用优化</a>
              </p>
              <p class="item-date">
                <time datetime="2025-07-18T11:53:08.000Z" itemprop="datePublished">2025-07-18</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/06/17/interview/" class="title">interview</a>
              </p>
              <p class="item-date">
                <time datetime="2025-06-17T03:52:38.000Z" itemprop="datePublished">2025-06-17</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2024/03/03/find-hamilton-path/" class="title">Javascript实现寻找哈密尔顿回路</a>
              </p>
              <p class="item-date">
                <time datetime="2024-03-03T00:18:45.000Z" itemprop="datePublished">2024-03-03</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2024/02/21/better-to-know-signature-and-certificate/" class="title">一文读懂加密，摘要，数字签名和证书</a>
              </p>
              <p class="item-date">
                <time datetime="2024-02-21T03:22:45.000Z" itemprop="datePublished">2024-02-21</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<main class="main" role="main">
  <div class="content">
  <article id="post-design-pub-sub" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      发布-订阅模式-- 《Javascript 设计模式与开发实践》
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/didiblog/2023/02/08/design-pub-sub/" class="article-date">
	  <time datetime="2023-02-08T04:42:36.000Z" itemprop="datePublished">2023-02-08</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/didiblog/categories/JS/">JS</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/didiblog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">设计模式</a>
  </span>


        

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/didiblog/2023/02/08/design-pub-sub/#comments" class="article-comment-link">评论</a></span>
        
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <h3 id="什么是发布-订阅模式"><a href="#什么是发布-订阅模式" class="headerlink" title="什么是发布-订阅模式"></a>什么是发布-订阅模式</h3><p>发布订阅模式，它定义了对象之间的一种一对多的依赖关系，当一个对象的状态发生变化时，所有依赖于它的对象都会接收到通知。</p>
<h3 id="生活中的发布-订阅模式"><a href="#生活中的发布-订阅模式" class="headerlink" title="生活中的发布-订阅模式"></a>生活中的发布-订阅模式</h3><p>其实我们生活中也有发布订阅模式的例子，比如小明想买某个楼盘的房子，他会打电话给售楼中心的销售人员，销售告诉他可惜卖完了，不过再过段时间就又有新房出售了，所以过了几天小明又来打电话询问房子的事情，结果新房又售罄了。小明很沮丧。我想现实生活中大家不会这么蠢自己每天打电话去问情况，实际上是小明只需要把联系方式留给销售，销售一有新房出售就立刻发信息通知小明。这样销售也不用每天接上百个重复的电话了。无论是小明，小红。只要在他这里留了联系方式的人，一并把信息全部出去，而且还可以附带一些房子的信息，比如房子面积，价格等。用代码实现功能之前我们先分析下需要做哪些东西。</p>
<ol>
<li>首先安排一个发布者，这个例子中应该是售楼的销售人员。</li>
<li>然后给发布者添加一个缓存列表，用于存放回调函数以便通知订阅者（销售人员手上的购房意向名单）</li>
<li>最后发布消息的时候，发布者会遍历这个缓存列表，依次出发里面存放的订阅者回调函数（挨个给他们发短信）</li>
</ol>
<h3 id="用发布订阅模式实现房产订购"><a href="#用发布订阅模式实现房产订购" class="headerlink" title="用发布订阅模式实现房产订购"></a>用发布订阅模式实现房产订购</h3><p> 下面就用代码实现上面的需求。<br> <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"> const salesOffices = &#123;&#125;; // 定义发布者</span><br><span class="line"></span><br><span class="line">salesOffices.clientList = []; // 创建缓存列表</span><br><span class="line"></span><br><span class="line">salesOffices.addListener = function(fn) &#123; // 添加订阅者</span><br><span class="line">    this.clientList.push(fn);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">salesOffices.trigger = function()&#123; // 发布消息</span><br><span class="line">    this.clientList.forEach((item, index) =&gt; &#123;</span><br><span class="line">        item.apply(this, arguments);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">salesOffices.addListener(function(price, sqaureMeter) &#123; // 小明订阅消息</span><br><span class="line">    console.log(&#x27;price is:&#x27;, price)</span><br><span class="line">    console.log(&#x27;sqaureMeter is:&#x27;, sqaureMeter)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">salesOffices.addListener(function(price, sqaureMeter) &#123; // 小红订阅消息</span><br><span class="line">    console.log(&#x27;price is:&#x27;, price)</span><br><span class="line">    console.log(&#x27;sqaureMeter is:&#x27;, sqaureMeter)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">salesOffices.trigger(8000, &quot;100平米&quot;);</span><br><span class="line">salesOffices.trigger(4000, &quot;90平米&quot;);</span><br></pre></td></tr></table></figure><br>至此，我们实现了一个最简单的发布-订阅模式，但是这里还存在一些问题，假设小明只想买90平及以下的房子，那么他也收到了100平房子的消息，显然这是不合理的。所以现在我们有必要增加一个标识key，让订阅者只订阅自己感兴趣的消息。那我们把代码稍微改动下。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">const salesOffices = &#123;&#125;; // 定义发布者</span><br><span class="line"></span><br><span class="line">salesOffices.clientList = &#123;&#125;; // 创建缓存列表</span><br><span class="line"></span><br><span class="line">salesOffices.addListener = function (key, fn) &#123; // 添加订阅者</span><br><span class="line">	if (!this.clientList[key]) &#123;</span><br><span class="line">		this.clientList[key] = [];</span><br><span class="line">	&#125;</span><br><span class="line">	this.clientList[key].push(fn);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">salesOffices.trigger = function () &#123; // 发布消息</span><br><span class="line">	const subKey = Array.prototype.shift.call(arguments);</span><br><span class="line">	const fns = this.clientList[subKey];</span><br><span class="line">	if (!fns || fns.length === 0) &#123;</span><br><span class="line">		return false;</span><br><span class="line">	&#125;</span><br><span class="line">	fns.forEach((fn) =&gt; &#123;</span><br><span class="line">		fn.apply(this, arguments);</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">salesOffices.addListener(&quot;sqaureMeter90&quot;, function (price, sqaureMeter) &#123; // 小明订阅消息</span><br><span class="line">	console.log(&#x27;price is:&#x27;, price)</span><br><span class="line">	console.log(&#x27;sqaureMeter is:&#x27;, sqaureMeter)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">salesOffices.addListener(&quot;sqaureMeter100&quot;, function (price, sqaureMeter) &#123; // 小红订阅消息</span><br><span class="line">	console.log(&#x27;price is:&#x27;, price)</span><br><span class="line">	console.log(&#x27;sqaureMeter is:&#x27;, sqaureMeter)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">salesOffices.trigger(&quot;sqaureMeter100&quot;, 8000, &quot;100平米&quot;);</span><br><span class="line">salesOffices.trigger(&quot;sqaureMeter90&quot;, 4000, &quot;90平米&quot;);</span><br></pre></td></tr></table></figure>
<p>现在用户只会收到订阅自己感兴趣的消息了。</p>
<h3 id="抽象发布订阅功能"><a href="#抽象发布订阅功能" class="headerlink" title="抽象发布订阅功能"></a>抽象发布订阅功能</h3><p>现在这个功能基本好用了，但是发布订阅是比较通用的功能，可能也会用在其他地方，现在我们把它抽象成一个单独的对象。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">const Event = &#123;</span><br><span class="line">	clientList: &#123;&#125;,</span><br><span class="line">	addListener: function (key, fn) &#123; // 添加订阅者</span><br><span class="line">		if (!this.clientList[key]) &#123;</span><br><span class="line">			this.clientList[key] = [];</span><br><span class="line">		&#125;</span><br><span class="line">		this.clientList[key].push(fn);</span><br><span class="line">	&#125;,</span><br><span class="line">	trigger: function () &#123; // 发布消息</span><br><span class="line">		const subKey = Array.prototype.shift.call(arguments);</span><br><span class="line">		const fns = this.clientList[subKey];</span><br><span class="line">		if (!fns || fns.length === 0) &#123;</span><br><span class="line">			return false;</span><br><span class="line">		&#125;</span><br><span class="line">		fns.forEach((fn) =&gt; &#123;</span><br><span class="line">			fn.apply(this, arguments);</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>然后再用上面的代码测试下</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">const salesOffices = Object.create(Event, &#123;&#125;); // 定义发布者</span><br><span class="line"></span><br><span class="line">salesOffices.addListener(&quot;sqaureMeter90&quot;, function (price, sqaureMeter) &#123; // 小明订阅消息</span><br><span class="line">	console.log(&#x27;price is:&#x27;, price)</span><br><span class="line">	console.log(&#x27;sqaureMeter is:&#x27;, sqaureMeter)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">salesOffices.addListener(&quot;sqaureMeter100&quot;, function (price, sqaureMeter) &#123; // 小红订阅消息</span><br><span class="line">	console.log(&#x27;price is:&#x27;, price)</span><br><span class="line">	console.log(&#x27;sqaureMeter is:&#x27;, sqaureMeter)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">salesOffices.trigger(&quot;sqaureMeter100&quot;, 8000, &quot;100平米&quot;);</span><br><span class="line">salesOffices.trigger(&quot;sqaureMeter90&quot;, 6000, &quot;90平米&quot;);</span><br></pre></td></tr></table></figure>
<p>结果都是一样的。</p>
<h3 id="取消订阅的事件"><a href="#取消订阅的事件" class="headerlink" title="取消订阅的事件"></a>取消订阅的事件</h3><p>如果哪一天小明买到房子了或者不想买了，他就不用继续订阅消息了，所以我们应该再添加一个可以取消订阅的功能。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">Event.remove = function (key, fnName) &#123;</span><br><span class="line">		const fns = this.clientList[key];</span><br><span class="line">		if (!fns || fns.length === 0) &#123;</span><br><span class="line">			return false;</span><br><span class="line">		&#125;</span><br><span class="line">		if (!fnName) &#123; // 如果没有传入对应的回调函数名，则认为移除所有的订阅</span><br><span class="line">			this.clientList[key] = [];</span><br><span class="line">		&#125; else &#123;</span><br><span class="line">			fns.forEach((fn, index) =&gt; &#123;</span><br><span class="line">				if (fn === fnName) &#123;</span><br><span class="line">					fns.splice(index, 1);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;)</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">    </span><br><span class="line">    const salesOffices = Object.create(Event, &#123;&#125;); // 定义发布者</span><br><span class="line"></span><br><span class="line">const mingSbuscrible = function (price, sqaureMeter) &#123; // 小明订阅消息</span><br><span class="line">	console.log(&#x27;ming price is:&#x27;, price)</span><br><span class="line">	console.log(&#x27;ming sqaureMeter is:&#x27;, sqaureMeter)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">const hongSubscrible =  function (price, sqaureMeter) &#123; // 小红订阅消息</span><br><span class="line">	console.log(&#x27;hong price is:&#x27;, price)</span><br><span class="line">	console.log(&#x27;hong sqaureMeter is:&#x27;, sqaureMeter)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">salesOffices.addListener(&quot;sqaureMeter100&quot;, mingSbuscrible)</span><br><span class="line"></span><br><span class="line">salesOffices.addListener(&quot;sqaureMeter100&quot;, hongSubscrible)</span><br><span class="line"></span><br><span class="line">salesOffices.remove(&quot;sqaureMeter100&quot;, mingSbuscrible) //小明移除了消息订阅</span><br><span class="line">salesOffices.trigger(&quot;sqaureMeter100&quot;, 8000, &quot;100平米&quot;); //只有小红收到了订阅消息</span><br></pre></td></tr></table></figure>
<p>好了，到此关于发布-订阅模式基本完成。当然针对这个模式的实践还有很多，但是其原理都是一致的，多敲两遍代码就会慢慢明白了。下面我们来总结下这个模式的优缺点吧。</p>
<h3 id="发布订阅模式的优缺点"><a href="#发布订阅模式的优缺点" class="headerlink" title="发布订阅模式的优缺点"></a>发布订阅模式的优缺点</h3><h4 id="优点"><a href="#优点" class="headerlink" title="优点"></a>优点</h4><ol>
<li>为时间和对象解耦，不用强耦合。你可以随意的添加订阅者而不受其他因素影响。</li>
<li>弱化对象之间的联系，可以实现一对多的对象关系，发布者只负责发布消息，不需要关系订阅者的状态。</li>
</ol>
<h4 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h4><ol>
<li>消耗一定的时间和内存，当你订阅了一个消息后，也许这个消息从未发出，但是这个订阅者始终会占用内存。</li>
<li>对象之间的联系被隐藏在背后，尤其当有多个发布者和订阅者嵌套到一起的时候，调试代码变得不那么容易。</li>
</ol>
<p>小伙伴们，喜欢的话，赶快在你们的代码中用起来吧。</p>
<blockquote>
<p>本文代码内容主要引用自曾探的《Javascript 设计模式与开发实践》</p>
</blockquote>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://guoyayunhappy.gitee.io/didiblog/2023/02/08/design-pub-sub/" title="发布-订阅模式-- 《Javascript 设计模式与开发实践》" target="_blank" rel="external">https://guoyayunhappy.gitee.io/didiblog/2023/02/08/design-pub-sub/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/GuoyayunHappy" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/didiblog/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/GuoyayunHappy" target="_blank"><span class="text-dark">一枚@大帅锅</span><small class="ml-1x">CV工程师</small></a></h3>
        <div>个人简介。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/didiblog/2023/02/08/design-stratage/" title="策略模式模式-- 《Javascript 设计模式与开发实践》"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/didiblog/2023/02/08/how-to-deal-with-cross-domain/" title="一个简单的案例带你了解并解决跨域以及跨域携带cookie的问题"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
  </ul>
  
  
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal" data-target="#donateModal"><span>赏</span></button>
  <!-- <div class="wave-icon wave-icon-danger btn-donate" data-toggle="modal" data-target="#donateModal">
    <div class="wave-circle"><span class="icon"><i class="icon icon-bill"></i></span></div>
  </div> -->
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  
<!-- Modal -->
<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content donate">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div class="modal-body">
        <div class="donate-box">
          <div class="donate-head">
            <p>感谢您的支持，我会继续努力的!</p>
          </div>
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="alipay">
              <div class="donate-payimg">
                <img src="/didiblog/images/donate/alipayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开支付宝扫一扫，即可进行扫码打赏哦</p>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="wechatpay">
              <div class="donate-payimg">
                <img src="/didiblog/images/donate/wechatpayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开微信扫一扫，即可进行扫码打赏哦</p>
            </div>
          </div>
          <div class="donate-footer">
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay" aria-expanded="true"><i class="icon icon-alipay"></i> 支付宝</a>
              </li>
              <li role="presentation" class="">
                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab" aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i> 微信支付</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>



</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://gitee.com/GuoyayunHappy" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/didiblog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/didiblog/js/plugin.min.js"></script>


<script src="/didiblog/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/didiblog/',
        CONTENT_URL: '/didiblog/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/didiblog/js/insight.js"></script>






   




   
    
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/valine"></script>
  <script type="text/javascript">
  var GUEST = ['nick', 'mail', 'link'];
  var meta = 'nick,mail,link';
  meta = meta.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#vcomments',
    verify: false,
    notify: false,
    appId: '',
    appKey: '',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: meta,
    pageSize: '10' || 10,
    visitor: false
  });
  </script>

     







</body>
</html>